<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\ExpressServiceProvider;
use think\facade\{Db, Log};
use think\Request;
use app\validate\ExpressServiceProviderValidate;

class ExpressServiceProviderController extends BaseController
{
    protected $validate;

    public function __construct(ExpressServiceProviderValidate $validate)
    {
        $this->validate = $validate;
    }

    /**
     * 服务商列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $where = [];
            //服务类型
            $service_type = $params['service_type'] ?? '1';
            if($service_type){
                $where['service_type'] = $service_type;
            }

            // 服务商类型搜索

            if (isset($params['service_type']) && $params['service_type'] !== '') {
                $where['service_type'] = $params['service_type'];
            }

            // 服务商名称搜索
            if (!empty($params['company_name'])) {
                $where[] = ['company_name', 'like', "%{$params['company_name']}%"];
            }


            // 服务商编码搜索
            if (!empty($params['service_code'])) {
                $where[] = ['service_code', 'like', "%{$params['service_code']}%"];
            }

            // 状态筛选
            if (isset($params['status']) && $params['status'] !== '') {
                $where['status'] = $params['status'];
            }

            //$page强制转int
            $page = (int)$params['page'] ?? 1;
            $limit = (int)$params['limit'] ?? 10;
            $list = ExpressServiceProvider::where($where)
                ->order('id', 'desc')

                ->page($page, $limit)
                ->select();

            $total = ExpressServiceProvider::where($where)->count();

            return json([
                'code' => 0,
                'msg' => '获取成功',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取快递服务商列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 添加服务商
     */
    public function add(Request $request)
    {
        Db::startTrans();
        try {
            $data = $request->post();

            // 验证数据
            if (!$this->validate->scene('add')->check($data)) {
                throw new \Exception($this->validate->getError());
            }

            // 验证利润率总和
            $profitCheck = $this->validate->checkProfitRate($data);
            if ($profitCheck !== true) {
                throw new \Exception($profitCheck);
            }

            // 创建服务商
            ExpressServiceProvider::create([
                'service_code' => $data['service_code'],
                'company_name' => $data['company_name'],
                'company_code' => $data['company_code'],
                'service_type' => $data['service_type'],
                'channel' => $data['channel'] ?? '',
                'description' => $data['description'] ?? '',
                'weight_index' => $data['weight_index'],
                'first_weight' => $data['first_weight'],
                'min_weight' => $data['min_weight'],
                'max_weight' => $data['max_weight'],
                'is_insured' => $data['is_insured'],
                'insure_fee' => $data['insure_fee'] ?? 0,
                'status' => ExpressServiceProvider::STATUS_ENABLED
            ]);

            Db::commit();
            return json(['code' => 0, 'msg' => '添加成功']);

        } catch (\Exception $e) {
            Db::rollback();
            Log::error('添加快递服务商失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 编辑服务商
     */
    public function update(Request $request, $id)
    {
        Db::startTrans();
        try {
            $data = $request->post();

            // 验证数据
            if (!$this->validate->scene('update')->check($data)) {
                throw new \Exception($this->validate->getError());
            }

            // 更新服务商
            $provider = ExpressServiceProvider::find($id);
            if (!$provider) {
                throw new \Exception('服务商不存在');
            }

            $provider->save([
                'company_name' => $data['company_name'],
                'service_type' => $data['service_type'],
                'channel' => $data['channel'] ?? '',
                'description' => $data['description'] ?? '',
                'weight_index' => $data['weight_index'],
                'first_weight' => $data['first_weight'],
                'min_weight' => $data['min_weight'],
                'max_weight' => $data['max_weight'],
                'is_insured' => $data['is_insured'],
                'insure_fee' => $data['insure_fee'] ?? 0,
            ]);

            Db::commit();
            return $this->success('编辑成功');

        } catch (\Exception $e) {
            Db::rollback();
            Log::error('编辑快递服务商失败: ' . $e->getMessage());
           return $this->error($e->getMessage());
        }
    }

    /**
     * 启用/禁用服务商
     */
    public function setStatus(Request $request)
    {
        try {
            $id = $request->post('id');
            $status = $request->post('status');

            if (!$id || !in_array($status, [ExpressServiceProvider::STATUS_ENABLED, ExpressServiceProvider::STATUS_DISABLED])) {
                throw new \Exception('参数错误');
            }

            $provider = ExpressServiceProvider::find($id);
            if (!$provider) {
                throw new \Exception('服务商不存在');
            }

            if ($status == ExpressServiceProvider::STATUS_ENABLED) {
                $provider->enable();
            } else {
                $provider->disable();
            }

            return json(['code' => 0, 'msg' => '操作成功']);

        } catch (\Exception $e) {
            Log::error('设置快递服务商状态失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 